package com.kqzz.common.exception;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.kqzz.common.api.response.Response;

/**
 * 无效token，resourceid不匹配异常处理
 */
@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,AuthenticationException authException)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		Gson gson = new Gson();
		String result = "";
        Throwable cause = authException.getCause();

        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        // 进入此处异常后，前端应重定向到登录页面
        try {
            if(cause instanceof InvalidTokenException) {
            	result = gson.toJson(new Response().logout("token过期或帐号重复登录"));
                response.getWriter().write(result);
            }else if(cause instanceof OAuth2AccessDeniedException){ // 对resourceid不匹配的请求拒绝
            	result = gson.toJson(new Response().failure("无权限访问当前资源"));
                response.getWriter().write(result);
            }else if(null==cause && authException instanceof InsufficientAuthenticationException){
            	result = gson.toJson(new Response().logout("token不存在,检查Authorization属性"));
                response.getWriter().write(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
